package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.poster.ColorFilter;
import com.stark.poster.DataProvider;
import com.stark.poster.FilterAdapter;
import com.stark.poster.PosterConst;
import com.stark.poster.PosterStyle;
import com.stark.poster.databinding.MenuPosterFilterBinding;
import com.stark.poster.lib.Layer;
import com.stark.poster.lib.Model;
import com.stark.poster.lib.OnLayerSelectListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.MyPosterAdapter;
import flc.ast.databinding.ActivityPosterBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.AssetUtil;
import stark.common.basic.utils.DensityUtil;
import stark.common.basic.utils.RxUtil;

public class PosterActivity extends BaseAc<ActivityPosterBinding> {

    private static final int MAX_COVER_WIDTH = 720;
    private static final int MAX_LAYER_WIDTH = 400;
    public static List<String> mPaths;
    private List<PosterStyle> mPosterStyleList = new ArrayList<>();
    private int mStylePos = 0;
    private Layer mSelectedLayer;

    @Override
    protected int onCreate() {
        return R.layout.activity_poster;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);
        mDataBinding.ivPosterBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivPosterSave.setOnClickListener(this);
        mPosterStyleList.addAll(DataProvider.getPosterStyle(mPaths.size(), this));
        mDataBinding.rvPosterList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        MyPosterAdapter myPosterAdapter = new MyPosterAdapter(R.layout.item_poster, mPosterStyleList);
        mDataBinding.rvPosterList.setAdapter(myPosterAdapter);
        myPosterAdapter.setOnItemClickListener(this);
        setModel();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivPosterSave:
                saveImg();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (mStylePos == position) {
            return;
        }
        mStylePos = position;
        mDataBinding.pvPoster.getModelView().setFirstDraw(true);
        setModel();
    }

    @Override
    protected void initData() {
        initMenuFilterView();
    }

    //保存图片
    private void saveImg() {
        showDialog(getString(R.string.save_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        File file = ImageUtils.save2Album(ImageUtils.view2Bitmap(mDataBinding.pvPoster.getModelView()), Bitmap.CompressFormat.PNG);
                        String path = PathUtils.getFilesPathExternalFirst() + Content.myImage + "/" + FileUtils.getFileName(file.getPath());
                        FileUtils.copy(file.getPath(), path);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        dismissDialog();
                        ToastUtils.showShort(getString(R.string.save_suc));
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                startActivity(HomeActivity.class);
                            }
                        }, 1000);
                    }
                });
            }
        }, 1000);
    }

    private void setModel() {
        RxUtil.create(new RxUtil.Callback<Boolean>() {
            @Override
            public void doBackground(ObservableEmitter<Boolean> emitter) {
                setModel(mStylePos);
                emitter.onNext(true);
            }

            @Override
            public void accept(Boolean obj) {
            }
        });
    }

    private void setModel(int pos) {
        PosterStyle posterStyle = mPosterStyleList.get(pos);
        String maskImage = posterStyle.getMaskImage();
        String backgroundImage = posterStyle.getBackgroundImage();
        List<Layer> layers = new ArrayList<>();
        try {
            Bitmap bitmapMask = null;
            if (!TextUtils.isEmpty(maskImage)) {
                bitmapMask = Glide.with(this).asBitmap()
                        .load(AssetUtil.getFilePath(PosterConst.DIR_POSTER_MASK, maskImage))
                        .submit(MAX_COVER_WIDTH, MAX_COVER_WIDTH)
                        .get();
            }
            Bitmap bitmapBg = Glide.with(this).asBitmap()
                    .load(AssetUtil.getFilePath(PosterConst.DIR_POSTER_BG, backgroundImage))
                    .submit(MAX_COVER_WIDTH, MAX_COVER_WIDTH)
                    .get();

            List<PosterStyle.SubViewInfoBean.ImageViewInfoBean> imageViewInfo = posterStyle.getSubViewInfo().getImageViewInfo();

            int i = 0;
            for (PosterStyle.SubViewInfoBean.ImageViewInfoBean subView : imageViewInfo) {
                Bitmap layerBitMap = Glide.with(this).asBitmap().load(mPaths.get(i)).submit(MAX_LAYER_WIDTH, MAX_LAYER_WIDTH).get();
                Layer layer = new Layer(layerBitMap, 0, subView.getAboveMask() == 1);
                for (String point : subView.getPointArray()) {
                    int[] points;
                    points = getPoint(point);
                    layer.markPoint(points[0], points[1]);
                }
                layer.build();
                i++;
                layers.add(layer);
            }
            Model model = new Model(bitmapBg, layers, bitmapMask);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mDataBinding.pvPoster.setModel(model);
                    mDataBinding.pvPoster.getModelView().setOnLayerSelectListener(onLayerSelectListener);
                }
            });
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public int[] getPoint(String source) {
        int[] target = {0, 0};
        if (source == null) {
            return target;
        }
        try {
            String[] arr;
            arr = source.trim().substring(1, source.length() - 1).split(",");
            target[0] = Math.round(Float.parseFloat(arr[0]));
            target[1] = Math.round(Float.parseFloat(arr[1]));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return target;
    }

    private void initMenuFilterView() {
        MenuPosterFilterBinding menuBinding = MenuPosterFilterBinding.inflate(getLayoutInflater());
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        menuBinding.rvFilter.setLayoutManager(layoutManager);

        FilterAdapter filterAdapter = new FilterAdapter();
        filterAdapter.setFilters(ColorFilter.getFilters());
        filterAdapter.setListener(onItemSelectListener);
        menuBinding.rvFilter.setAdapter(filterAdapter);

        mDataBinding.pvPoster.addMenuInit(menuBinding.getRoot(), DensityUtil.getWith(this) - SizeUtils.dp2px(100), SizeUtils.dp2px(60));
    }

    private FilterAdapter.OnItemSelectListener onItemSelectListener = new FilterAdapter.OnItemSelectListener() {
        @Override
        public void selected(float[] filter) {
            if (mSelectedLayer != null) {
                if (filter != null) {
                    Bitmap bitmap = ColorFilter.setColorMatrix(mSelectedLayer.getLayer(), filter, false);
                    mSelectedLayer.setFilterLayer(bitmap);
                } else {
                    mSelectedLayer.clearFilter();
                }
                mDataBinding.pvPoster.getModelView().invalidate();
            }
        }
    };

    private OnLayerSelectListener onLayerSelectListener = new OnLayerSelectListener() {
        @Override
        public void onSelected(Layer layer) {
            mSelectedLayer = layer;
            mDataBinding.pvPoster.showMenu(layer);
        }

        @Override
        public void dismiss(Layer layer) {
            //怕有冲突加额外的判断
            if (mSelectedLayer == layer) {
                mSelectedLayer = null;
                mDataBinding.pvPoster.dismissMenu();
            }
        }
    };

}